
# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children


class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if not root:
            return []
        out = []
        stack = [root]
        stack_index = [0]
        while stack:
            node = stack[-1]
            if stack_index[-1] == 0:
                out.append(node.val)
            if node.children and stack_index[-1] < len(node.children):
                stack.append(node.children[stack_index[-1]])
                stack_index[-1] += 1
                stack_index.append(0)
            else:
                stack.pop()
                stack_index.pop()
        return out
